package com.lhf.aicloud.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lhf.aicloud.entity.Answer;
import com.lhf.aicloud.entity.enums.AIModelEnum;
import com.lhf.aicloud.entity.enums.AITypeEnum;
import com.lhf.aicloud.service.IAnswerService;
import com.lhf.aicloud.utils.AppVariable;
import com.lhf.aicloud.utils.ResponseEntity;
import com.lhf.aicloud.utils.SecurityUtils;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author: lhf
 * @date: Created in 2024/08/17
 * @description: 字节豆包大模型对接
 */
@Slf4j
@RestController
@RequestMapping("/doubao")
public class DouBaoController {

    @Value("${doubao.api-key}")
    private String apiKey;

    @Value("${doubao.url}")
    private String url;

    @Value("${doubao.model-id}")
    private String modelId;

    @Resource
    private IAnswerService answerService;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 对话功能
     */
    @RequestMapping("/chat")
    public ResponseEntity chat(String question) {
        if (!StringUtils.hasLength(question.trim())) {
            return ResponseEntity.error(400, "问题不能为空");
        }
        log.info("question: {}", question);

        // 1. 根据 api-key 和 服务地址 创建 ArkService 对象
        ArkService service = ArkService.builder().apiKey(apiKey)
                .baseUrl(url).build();

        // 2. 构建问题对象
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(question).build();
        messages.add(userMessage);

        // 3. 创建调用对象
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                // 接入点的ID
                .model(modelId)
                .messages(messages)
                .build();

        // 4. 得到对话结果
        String result = service.createChatCompletion(chatCompletionRequest).getChoices()
                .getFirst().getMessage().getContent().toString();

        log.info("result: {}", result);

        // 5. 将结果保存到 数据库
        Answer answer = new Answer();
        answer.setQuestion(question);
        answer.setAnswer(result);
        answer.setModel(AIModelEnum.DOUBAO.getValue());
        answer.setCreatetime(LocalDateTime.now());
        answer.setUid(Objects.requireNonNull(SecurityUtils.getCurrentUser()).getUid());
        answer.setType(AITypeEnum.CHAT.getValue());
        boolean addResult = answerService.save(answer);
        if (addResult) {
            return ResponseEntity.success(result);
        }
        return ResponseEntity.error("数据保存失败！");
    }


    /**
     * 获取豆包大模型聊天历史信息
     */
    @RequestMapping("/chatHistory")
    public ResponseEntity chatHistory() {
        // 获取当前用户ID
        Long uid = Objects.requireNonNull(SecurityUtils.getCurrentUser()).getUid();
        String cacheKey = AppVariable.getListCacheKey(uid, AIModelEnum.DOUBAO.getValue(), AITypeEnum.CHAT.getValue());
        ArrayList cacheList = (ArrayList)redisTemplate.opsForValue().get(cacheKey);
        if (cacheList != null && !cacheList.isEmpty()) {
            return ResponseEntity.success(cacheList);
        }
        // 构建查询条件
        LambdaQueryWrapper<Answer> answerLambdaQueryWrapper = new LambdaQueryWrapper<Answer>()
                .eq(Answer::getUid, uid)
                .eq(Answer::getType, AITypeEnum.CHAT.getValue())
                .eq(Answer::getModel, AIModelEnum.DOUBAO.getValue())
                .orderByDesc(Answer::getCreatetime);
        // 查询
        List<Answer> list = answerService.list(answerLambdaQueryWrapper);
        redisTemplate.opsForValue().set(cacheKey, list, 1, TimeUnit.DAYS);
        return ResponseEntity.success(list);
    }
}
